﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Text;

using FRL.DebtChased.Extensions;
using FRL.DebtChased.WebServices;
using System.IO;

namespace FRL.DebtChased.Repository
{

	/// <summary>
	/// Extensions to the Document entity
	/// </summary>
	public partial class Document
	{

		/////////////////////////////////////////////////////////////
		// Constants

		private const string FileNamePrefix = "DebtChasedDocument-";

		/////////////////////////////////////////////////////////////
		// Static Operations

		public static string Delete(DebtChasedEntities ent, int iDocumentId, string strDocumentFolderPath, int iUserId)
		{

			// Declare return variable
			string strFtmp = null;

			try
			{

				// Load the document and delete
				Document doc = (from d in ent.Documents
							   where d.DocumentId == iDocumentId
							   select d).FirstOrDefault();

				// Compose document filepath
				string strFilepath = Document.SafeComposeFilepath(strDocumentFolderPath,doc.FileName);

				// Track user actions
				UserAction.Session session = new UserAction.Session(iUserId, doc, doc.DocumentName);

				// Delete document
				ent.Documents.DeleteObject(doc);

				// Delete attached invoices
				List<DocumentAccountInvoice> daiList = (from dai in ent.DocumentAccountInvoices where dai.DocumentId == iDocumentId select dai).ToList();
				foreach (DocumentAccountInvoice dai in daiList)
					ent.DocumentAccountInvoices.DeleteObject(dai);

				// Save document
				ent.SaveChanges();

				// Delete the file
				if(File.Exists(strFilepath))
					File.Delete(strFilepath);

				// Save user changes
				session.SaveChanges(ent);

			}
			catch (Exception x)
			{

				// Update error
				strFtmp = ErrorProcessing.HandleException(x, "deleting document", iUserId);

			}

			// Return variable
			return strFtmp;

		}

		public static string Add(
			DebtChasedEntities ent,
			int iClientId,
			string strFileName,
			string strDocumentName,
			int iBytes,
			out int iNewDocumentId,
			int iUserId
		)
		{

			// Declare return variable
			string strFtmp = null;

			// Reset function parameters
			iNewDocumentId = 0;

			try
			{

				// Add new document entity object
				Document newDoc = Document.CreateDocument(
					0,
					iClientId,
					strFileName,
					iBytes,
					strDocumentName
				);
				ent.Documents.AddObject(newDoc);

				// Track user actions
				UserAction.Session session = new UserAction.Session(iUserId, newDoc, strDocumentName);

				// Save document
				ent.SaveChanges();

				// Update function parameter
				iNewDocumentId = newDoc._DocumentId;

				// Save user changes
				session.SaveChanges(ent);

			}
			catch (Exception x)
			{

				// Update error
				strFtmp = ErrorProcessing.HandleException(x, "adding document", iUserId);

			}

			// Return variable
			return strFtmp;

		}

		public static string ComposeDownloadUrl(string strDocumentFolderUrl, string strFilename)
		{

			// Get the file-name guid
			string strPrefix = strFilename.Substring(FileNamePrefix.Length, 2);

			// Get the folder path - first index
			string strFtmp = Path.Combine(
				strDocumentFolderUrl,
				string.Format("_{0}_", char.ToUpper(strPrefix[0]))
			);

			// Get the folder path - second index
			strFtmp = Path.Combine(
				strFtmp,
				string.Format("_{0}_", char.ToUpper(strPrefix[1]))
			);

			// Add file name
			strFtmp = Path.Combine(strFtmp, strFilename);

			// Use forward slashes
			strFtmp = strFtmp.Replace("\\", "/");

			// Return variable
			return strFtmp;

		}

		public static string SafeComposeFilepath( string strDocumentFolderPath, string strFilename )
		{

			// Get the file-name guid
			string strPrefix = strFilename.Substring(FileNamePrefix.Length, 2);

			// Get the folder path - first index
			string strFtmp = Path.Combine(
				strDocumentFolderPath, 
				string.Format("_{0}_",char.ToUpper(strPrefix[0]))
			);
			if (!Directory.Exists(strFtmp))
				Directory.CreateDirectory(strFtmp);

			// Get the folder path - second index
			strFtmp = Path.Combine(
				strFtmp, 
				string.Format("_{0}_",char.ToUpper(strPrefix[1]))
			);
			if (!Directory.Exists(strFtmp))
				Directory.CreateDirectory(strFtmp);

			// Add file name
			strFtmp = Path.Combine(strFtmp, strFilename);

			// Return variable
			return strFtmp;

		}

		public static string ComposeNewFilename(string strExtension)
		{
#if DEBUG
			Debug.Assert(
				(string.Compare(strExtension, ".pdf", true) == 0)
				||
				(string.Compare(strExtension, ".docx", true) == 0)
			);
#endif // #if DEBUG

			// Compose filename
			return string.Format("{0}{1}{2}", FileNamePrefix, Guid.NewGuid(), strExtension);

		}

	}

}
